package com.thinkgem.jeesite.modules.wx.mp;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thinkgem.jeesite.modules.wx.service.WeixinService;

import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * @author Binary Wang
 */
@Controller
@RequestMapping("/wechat")
public class WxMpPortalController {
	@Autowired
	private WeixinService wxService;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@ResponseBody
	@RequestMapping(value = "/api/{key}", produces = "application/xml; charset=UTF-8")
	public String handle(HttpServletRequest req, @PathVariable("key") String key,
			@RequestBody(required = false) String requestBody, @RequestParam("signature") String signature,
			@RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce,
			@RequestParam(name = "encrypt_type", required = false) String encType,
			@RequestParam(name = "msg_signature", required = false) String msgSignature,
			@RequestParam(name = "echostr", required = false) String echostr) {

		if (wxService.check(timestamp, nonce, signature, key)) {
			if ("GET".equalsIgnoreCase(req.getMethod())) {
				this.logger.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
				return echostr;
			} else {
				this.logger.info(
						"\n接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}],"
								+ " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
						signature, encType, msgSignature, timestamp, nonce, requestBody);
				String out = null;
				if (encType == null) {
					// 明文传输的消息
					WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
					WxMpXmlOutMessage outMessage = wxService.route(inMessage);
					if (outMessage == null) {
						return "";
					}

					out = outMessage.toXml();
				} else if ("aes".equals(encType)) {
					// aes加密的消息
					WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody,
							wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
					this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
					WxMpXmlOutMessage outMessage = wxService.route(inMessage);
					if (outMessage == null) {
						return "";
					}

					out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
				}
				this.logger.debug("\n组装回复信息：{}", out);

				return out;
			}
		}
		return "非法请求";
	}

}
